package sword.chapter9Heap;

import java.util.PriorityQueue;

/**
 * 数据流的第k大数值
 *
 * 最小堆，计算数据集中第k个值最大的元素
 *
 * @author K
 * @date 2021-12-13 21:49
 */
public class S59KthLargest {
    private PriorityQueue<Integer> minHeap;
    private Integer size;

    S59KthLargest(int k, int[] nums) {
        size = k;
        //默认创建的最小堆
        minHeap = new PriorityQueue<>();
        for (int num : nums) {
            add(num);
        }
    }

    public Integer add(int num) {
        if (minHeap.size() < size) {
            minHeap.offer(num);
        } else if(num > minHeap.peek()) {
            minHeap.poll();
            minHeap.offer(num);
        }

        return minHeap.peek();
    }

    public static void main(String[] args) {
        int[] nums = {4, 5, 8, 2};
        S59KthLargest largest = new S59KthLargest(3, nums);
        Integer result = largest.minHeap.peek();
        System.out.println();
    }

}
